$(function () {
    layui.use(['laydate', 'laytpl', 'table', 'form', 'formSelects', 'layer', 'util', 'soulTable','locals'], function () {
        var laydate = layui.laydate,
            laytpl = layui.laytpl,
            table = layui.table,
            form = layui.form,
            formSelects = layui.formSelects,
            layer = layui.layer,
            util = layui.util,
            soulTable = layui.soulTable,
            locals = layui.locals;
        form.render();
        var pageName = getPageName();
        var localParam = locals.get(pageName);
        var areaArr = [], timer = null, tbIndex = null,allAreas = [] ,allMeters = [];
        var max = util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');
        var param = {};
        var datetype = {
            1: {type: 'date', format: 'yyyy-MM-dd', text: '明细'},
            2: {type: 'month', format: 'yyyy-MM', text: '日报'},
            3: {type: 'year', format: 'yyyy', text: '周报'},
            4: {type: 'year', format: 'yyyy', text: '月报'}
        };
        var devTypeObj = {
            1: {name: '水', unit:'T'},
            0: {name: '电', unit:'kW·h'}
        };
        formSelects.btns('typeMenu', []);

        initAll();
        function initAll() {
            getAllAreas();
        }

        // 给筛选条件赋值
        function getLocalsParamData() {
            // 判断是否有缓存
            if(localParam){ // 有缓存
                param.repType = localParam.dateObj == undefined ? '2' : localParam.repType;
                if(localParam.dateObj){
                    param.dateObj = Object.assign({}, localParam.dateObj);
                }else{
                    param.dateObj = Object.assign({}, {
                        1: defaultSTime('1'),
                        2: defaultSTime('2'), // 日 ， 某月所有天
                        3: defaultSTime('3'), // 周 ， 某年所有周
                        4: defaultSTime('4') // 月 ， 某年所有周
                    });
                }
            }else{ // 无缓存，初始化
                param.repType = $('.repType :selected').val();
                param.dateObj = Object.assign({}, {
                    1: defaultSTime('1'),
                    2: defaultSTime('2'), // 日 ， 某月所有天
                    3: defaultSTime('3'), // 周 ， 某年所有周
                    4: defaultSTime('4') // 月 ， 某年所有周
                });
            }
            locals.set(pageName, param);
            // 赋值
            form.val('search',{repType: param.repType});
            form.render('select');
            initDate(param.repType, param.dateObj[param.repType]);
            $('.refreshBtn').click();
        }

        function initDate(repType, st) {
            laydate.render({
                elem: "#startTime",
                value: st,
                type: datetype[repType].type,
                format: datetype[repType].format,
                trigger: 'click',
                max: max,
                done: function(value){
                    param.dateObj[repType] = value;
                    locals.set(pageName, param);
                    if(timer){
                        clearTimeout(timer);
                    }
                    setTimeout(function(){
                        $(".refreshBtn").click();
                    },0);
                }
            });
        }

        // 监听报表类型
        form.on('select(repType)', function (data) {
            $('#startTime').remove();
            $('.startTime').html('<input type="text" class="layui-input" id="startTime" name="fromTime">');
            param.repType = data.value;
            locals.set(pageName, param);
            initDate(data.value, param.dateObj[param.repType]);
            $(".refreshBtn").click();
        });

        function getAllAreas() {
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allAreas = result;
                        var getTpl = $('#area-tpl').html();
                        laytpl(getTpl).render(result, function (html) {
                            $('.areaMenu').html(html);
                            formSelects.render('areaMenu');
                            formSelects.btns('areaMenu', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                            formSelects.value('areaMenu', 'val');
                            if(localParam){
                                param.area = localParam.area;
                                param.deviceTypeCode = localParam.deviceTypeCode;
                            }else{
                                areaArr = allAreas.map(function (item) {
                                    return item.areaId
                                });
                                param.area = areaArr;
                                param.deviceTypeCode = '0';
                            }
                            formSelects.value('areaMenu', param.area);
                            formSelects.value('typeMenu', [param.deviceTypeCode]);
                            getAllMeters();
                        });


                    }
                }
            });
        }

        function getAllMeters() {
            let type = param.deviceTypeCode == undefined ? '0' : param.deviceTypeCode;
            $.ajax({
                type: "GET",
                url: ctx + "/report/getAllMetersNoStatus.do",
                data: {
                    deviceTypeCode: type
                },
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allMeters = result.sort(compare('areaId'));
                        let meters = [];
                        result.forEach(function (item) {
                            param.area.forEach(function (val) {
                                if(item.areaId == val){
                                    meters.push(item)
                                }
                            })
                        });
                        var getTpl = $('#meter-tpl').html();
                        laytpl(getTpl).render(meters, function (html) {
                            $('.meterMenu').html(html);
                            formSelects.render('meterMenu');
                            formSelects.btns('meterMenu', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                            formSelects.value('meterMenu', 'val');
                        });
                        // getLocalsParamData()
                        // assignValue();
                        if(localParam && localParam.meter.length > 0){
                            param.meter = localParam.meter;
                        }else{
                            param.meter = allMeters.map(function(item){
                                return item.meterCode
                            });
                        }
                        formSelects.value('meterMenu', param.meter);
                        locals.set(pageName, param);
                        getLocalsParamData();
                    }
                }
            });
        }

        function filterMeters(areaArr) {
            var list = [], meters = [], typeMeter = [];
            allMeters.forEach(function(item){
                areaArr.forEach(function(val){
                    if(item.areaId == val){
                        typeMeter.push(item);
                    }
                });
            });
            let typeMeterArr = typeMeter.filter(function (val) {
                return val.deviceTypeCode == param.deviceTypeCode
            });
            typeMeterArr.forEach(function (ite) {
                meters.push(ite.meterCode);
                list.push({"name": ite.areaName, "type": "optgroup"});
                list.push({"name": ite.deviceName + '_' + ite.anotherName, "value": ite.meterCode});
            });
            formSelects.data('meterMenu', 'local', {
                arr: uniqObjInArray(list)
            });
            formSelects.value('meterMenu', meters);
            param.area = [].concat(areaArr);
            param.meter = [].concat(meters);
            locals.set(pageName, param);
            if(timer){
                clearTimeout(timer);
            }
            setTimeout(function(){
                $(".refreshBtn").click();
            },0);
        }

        /* 监听区域多选
        * id:点击select的id
        * vals:当前select已选中的值
        * val:当前select点击的值
        * isAdd:当前操作选中or取消
        * isDisabled:当前选项是否是disabled
        * */
        formSelects.on('areaMenu', function(id, vals, val, isAdd, isDisabled){
            areaArr.length = [];
            areaArr = vals.map(function(item){
                return item.value
            });
            filterMeters(areaArr);
        }, true);

        // 监听设备多选
        // 监听设备select是否展开
        let meterMenuIsOpen = false;
        formSelects.opened('meterMenu', function(id){
            meterMenuIsOpen = true;
        });
        formSelects.closed('meterMenu', function(id){
            meterMenuIsOpen = false;
        });
        // 监听鼠标在设备select中是否点击，无点击后延迟500ms发送查询请求
        $(".dev-option-wrap").on('mouseup','.xm-select-dl',function(event){
            if(meterMenuIsOpen){
                if(event.button == 0){ //鼠标左键
                    // console.log('按下')
                    setTimeout(function () {
                        let valArr = formSelects.value('meterMenu', 'val');
                        if(valArr.length > 0){
                            param.meter = valArr;
                            locals.set(pageName, param);
                            $(".refreshBtn").click();
                        }
                    },500)
                }
            }
        });

        // 监听水电表切换
        formSelects.on('typeMenu', function(id, vals, val, isAdd, isDisabled){
            if(vals.length === 0){
                layer.alert('请选择设备类型')
            }else{
                if(param.deviceTypeCode === val.value){
                    return false
                }else{
                    param.deviceTypeCode = val.value;
                    param.meter = [];
                    locals.set(pageName, param);
                    localParam = locals.get(pageName);
                    getAllMeters();
                }
            }
        }, true);

        //判断权限
        function hasAuth(authCode) {
            var authArray = authStr.split(",");
            if (authArray && authArray.length > 0) {
                for (var i = 0; i < authArray.length; i++) {
                    if (authArray[i].trim() == authCode) {
                        return true;
                    }
                }
            }
            return false;
        }

        //点击刷新
        $('.searchBtn').click(function () {
            $(".refreshBtn").click();
        });
        $(".refreshBtn").click(function () {
            form.on('submit(search)', function (data) {
                getDevices(data.field);
                locals.set(pageName, param);
                return false;
            });
        });

        function getDevices(datas) {
            $.ajax({
                type: "POST",
                url: ctx + "/report/queryReports.do",
                data: datas,
                dataType: "json",
                success: function (result) {
                    if (result.data) {
                        var list = result.data;
                        // var maxv = getObjArrMax(list,'intervalQuantity').length; // 最大值的数字位数
                        var temp = [];
                        var obj = {};
                        list.forEach(function (item) {
                            var data = list.filter(function (val) {
                                return val.meterCode == item.meterCode
                            });
                            var tempObj = {};
                            data.forEach(function (ite) {
                                let str = '';
                                switch (datas.repType) {
                                    // case '1' :
                                    //     return ite.detailDate;
                                    //     break;
                                    case '2' :
                                        str = ite.day;
                                        break;
                                    case '3' :
                                        str = ite.week;
                                        break;
                                    case '4' :
                                        str = ite.month;
                                        break;
                                }
                                tempObj[str] = ite.intervalQuantity
                            });
                            obj[item.meterCode] = {
                                anotherName: item.anotherName
                            };
                            obj[item.meterCode] = Object.assign(obj[item.meterCode], tempObj);
                        });
                        temp = Object.values(obj);
                        var col = [{field: "anotherName", title: "设备", width: 100, fixed: 'left', totalRowText: '合计'}];
                        var ymd = datas.fromTime.split(' ')[0];
                        // 模拟数据
                        if (datas.repType == 1) { //明细
                            for (var i = 0; i < 24; i++) {
                                var h = i < 10 ? "0" + i : i;
                                col.push({field: ymd + ' ' + h, title: h + ":00", totalRow: true});
                            }
                        } else if(datas.repType == 2){ // 日
                            var year = datas.fromTime.split('-')[0];
                            var month = datas.fromTime.split('-')[1]; //所选月份
                            var len = getAMonthDays(year, month); //所选月份的天数
                            for (var i = 1; i <= len; i++) {
                                var day = i < 10 ? "0" + i : i;
                                col.push({field: year + '-' + month + '-' + day, title: parseInt(month) + "月" + i + "日", totalRow: true});
                            }
                        } else if (datas.repType == 3){ // 周
                            var year = (datas.fromTime).substr(2); // 2021 取 21
                            var len = getNumOfWeeks(datas.fromTime);
                            for (var i = 1; i <= len; i++) {
                                var week = i < 10 ? '0' + i : i;
                                col.push({field: datas.fromTime + week , title: year + week + '周', totalRow: true});
                            }
                        } else if (datas.repType == 4){ // 月
                            for (var i = 1; i <= 12; i++) {
                                let MM = i < 10 ? '0'+i : i;
                                col.push({field: datas.fromTime + '-' + MM, title: i + '月' , totalRow: true});
                            }
                        }
                        renderTable(temp, col);
                        // 报表标题
                        var title = $('#startTime').val() + '设备统计'+ datetype[datas.repType].text +'表';
                        let unit = '<span>单位：'+ devTypeObj[param.deviceTypeCode].unit +'</span>';
                        $(".title").html(title + unit);
                    } else if (result.message) {
                        console.info(result.message);
                    }
                }
            });

        }

        //勾选的水表表格
        function renderTable(data, col) {
            var tbHeigth = $('.main-part').height() - 44;
            // var cellMin = maxv <= 5 ? 45 : 50;
            tbIndex = table.render({
                elem: '#reports'
                , id: 'myTable'
                , data: data
                , heigth: tbHeigth
                , drag: false // 关闭拖拽列功能
                , title: '报表'
                , size: 'sm'
                , defaultToolbar: []
                , cols: [col]
                , limit: data.length
                // , page: {
                //     layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                //     , groups: 5 //只显示 5 个连续页码
                //     , limit: 15  //每页显示条数
                //     , limits: [15, 30, 45, 60]
                // }
                , totalRow: true
                , loading: true
                , done: function (res, curr, count) {
                    // $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    // $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                    let totalrow = $('.layui-table-total td:not([data-field="anotherName"]) .layui-table-cell');
                    for(let i=0;i<totalrow.length;i++){
                        $(totalrow[i]).text(parseFloat($(totalrow[i]).text()).toFixed(1))
                    }
                    soulTable.render(this);
                }
            });
        }

        // 导出excel
        $('.exportBtn').click(function () {
            soulTable.export('myTable', {filename: $(".title").text() + '.xlsx'});
        });

        /*对象数组中，取指定属性的最大值*/
        function getObjArrMax(arr,field){
            var temp = [];
            if(arr.length == 0){
                return '';
            }else{
                arr.forEach(item => {
                    temp.push(item[field])
                });
                return '' + Math.max.apply(null, temp);
            }
        }

        /* 设置开始时间：
        * parm ： type
        *  1明细： 当天0点 、
        *  2日： 当月1号、
        *  3周： 本年、
        *  4年： 本年
        *  */
        function defaultSTime(type) {
            var str = '';
            switch (type) {
                case '1':
                    str = util.toDateString(new Date(), 'yyyy-MM-dd');
                    break;
                case '2':
                    str = util.toDateString(new Date(), 'yyyy-MM');
                    break;
                case '3':
                    str = util.toDateString(new Date(), 'yyyy');
                    break;
                case '4':
                    str = util.toDateString(new Date(), 'yyyy');
                    break;
            }
            return str;
        }

        // 打印
        $('.printBtn').click(function () {
            createPrintTable();
            // 创建iframe，填入需要打印的内容和样式
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",
                    "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
                    "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
                    "thead tr th:first-child,tbody tr td:first-child{width:80px}",
                    "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", ".ptitle{font-size:16px;font-weight:bold;text-align:center;}" ,"</style>"].join(""),
                printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
                ptitle = $('<div class="ptitle">' + $('#printcontent .title').text() + '</div>');
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
            printHtml.find("th.layui-table-patch").remove();
            printHtml.find(".layui-table-col-special").remove();
            doc.write(style + ptitle.prop("outerHTML") +printHtml.prop("outerHTML"));
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            iframe.remove();
            $('#printContentBox').empty();
        });

        function createPrintTable() {
            $('#printContentBox').html('<table id="printTb"></table>');
            var temp = tbIndex.config;
            // 所有数据加载为新表格
            table.render({
                elem: '#printTb'
                , data: temp.data
                , cellMinWidth: 48
                , size: 'sm'
                , defaultToolbar: []
                , cols: temp.cols
                , limit: temp.data.length
            })
        }
    });
});
